<!--店铺管理-->
<script setup lang="ts">
  import {AxiosPromise} from "axios";

  defineOptions({
    name: "BillLock",
    inheritAttrs: false,
  });

  import {
    getBillLockPage,
    getBillLockForm,
    saveBillLock,
    deleteBillLock,
  } from "@/api/billLock";

  import { BillLockQuery, BillLockForm } from "@/api/billLock/types";
  import {StoreVO} from "@/api/store/types";
  import {listAll} from "@/api/store";
  import lodash from "lodash-es";

  const queryFormRef = ref(ElForm);
  const dataFormRef = ref(ElForm);

  const loading = ref(false);
  const ids = ref<number[]>([]);
  const total = ref(0);
  const storeOptions = ref<StoreVO[]>();

  const queryParams = reactive<BillLockQuery>({
    pageNum: 1,
    pageSize: 20,
  });

  const billLockList = ref<[]>();

  const dialog = reactive<DialogOption>({
    visible: false,
  });

  const formData = reactive<BillLockForm>({});

  const rules = reactive({

  });

  /**
   * 查询
   */
  function handleQuery() {
    loading.value = true;
    getBillLockPage(queryParams)
            .then(({ data }) => {
              billLockList.value = data.list;
              total.value = data.total;
            })
            .finally(() => {
              loading.value = false;
            });
  }

  /**
   * 重置查询
   */
  function resetQuery() {
    queryFormRef.value.resetFields();
    queryParams.pageNum = 1;
    handleQuery();
  }

  /**
   * 行checkbox change事件
   */
  function handleSelectionChange(selection: any) {
    ids.value = selection.map((item: any) => item.id);
  }

  /**
   * 字典类型表单提交
   */
  function handleSubmit() {
    dataFormRef.value.validate((isValid: boolean) => {
      if (isValid) {
        saveBillLock(formData)
                .then(() => {
                  ElMessage.success("保存成功");
                  closeDialog();
                  handleQuery();
                })
                .finally(() => (loading.value = false));
      }
    });
  }

  /**
   * 打开字典类型表单弹窗
   *
   * @param dicTypeId 字典类型ID
   */
  async function openDialog(id?: number) {
    dialog.visible = true;
    if (id) {
      dialog.title = "修改核销锁账";
      getBillLockForm(id).then(({ data }) => {
        Object.assign(formData, data);
      });
    } else {
      dialog.title = "新增店铺账号";
    }
  }

  /**
   * 关闭弹窗
   */
  function closeDialog() {
    dialog.visible = false;
    resetForm();
  }

  /**
   * 重置表单
   */
  function resetForm() {
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();

    formData.id = undefined;
  }

  /**
   * 删除事件
   */
  function handleDelete(dictTypeId?: number) {
    const dictTypeIds = [dictTypeId || ids.value].join(",");
    if (!dictTypeIds) {
      ElMessage.warning("请勾选删除项");
      return;
    }

    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      deleteBillLock(dictTypeIds).then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      });
    });
  }

  const dictDataDialog = reactive<DialogOption>({
    visible: false,
  });

  function getAllStore() {
	  listAll().then((response) => {
		  storeOptions.value = []
		  const group_store = lodash.groupBy(response.data, 'storeKeyName');
		  for (let key in group_store) {
			  storeOptions.value.push({'label': key, 'options': group_store[key]})
		  }
	  })
  }

  onMounted(() => {
    handleQuery();
	  getAllStore()
  });
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="电商平台店铺名称" prop="keywords">
					<el-select class="yz-el-select" v-model="queryParams.keywords" filterable clearable placeholder="请选择电商平台店铺名称">
						<el-option-group
								v-for="group in storeOptions"
								:key="group.label"
								:label="group.label"
						>
							<el-option
									v-for="item in group.options"
									:key="item.id"
									:label="item.commercePlatformStoreName"
									:value="item.commercePlatformStoreCode"
							/>
						</el-option-group>
					</el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
          ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button
								v-hasPerm="['sys:billLock:delete']"
                type="danger"
                :disabled="ids.length === 0"
                @click="handleDelete()"
        ><i-ep-delete />删除</el-button
        >
      </template>
      <el-table
              size="small"
              :header-row-style="{color: 'dimgray'}"
              v-loading="loading"
              highlight-current-row
              :data="billLockList"
              border
			  			:height="billLockList && billLockList.length > 0 ? 580 : 130"
              @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="所属平台" prop="commercePlatformStoreCode"/>
        <el-table-column label="电商平台店铺名称" prop="commercePlatformStoreName"/>
        <el-table-column label="初始日期" prop="billDateStart"/>
        <el-table-column label="关账日期" prop="billDateEnd"/>
        <el-table-column label="是否需要核销" prop="auditTypeName"/>
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
                    v-hasPerm="['sys:billLock:save']"
                    type="primary"
                    link
                    size="small"
                    @click.stop="openDialog(scope.row.id)"
            ><i-ep-edit />编辑</el-button
            >
            <el-button
                    v-hasPerm="['sys:billLock:delete']"
                    type="primary"
                    link
                    size="small"
                    @click.stop="handleDelete(scope.row.id)"
            ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
              v-if="total > 0"
              v-model:total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
            v-model="dialog.visible"
            :title="dialog.title"
            width="500px"
            :close-on-click-modal="false"
            @close="closeDialog"
    >
      <el-form
              ref="dataFormRef"
              :model="formData"
              :rules="rules"
              label-width="150px"
      >
        <el-form-item label="电商平台店铺编码" prop="commercePlatformStoreCode">
          <el-input v-model="formData.commercePlatformStoreCode" disabled/>
        </el-form-item>
        <el-form-item label="电商平台店铺名称" prop="commercePlatformStoreName">
          <el-input v-model="formData.commercePlatformStoreName" disabled/>
        </el-form-item>
        <el-form-item label="初始日期" prop="billDateStart">
          <el-date-picker
                  v-model="formData.billDateStart"
                  type="date"
                  value-format="YYYY-MM-DD"
                  :editable="false"
                  :clearable="true"
                  placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="关账日期" prop="billDateEnd">
          <el-date-picker
                  v-model="formData.billDateEnd"
                  type="date"
                  value-format="YYYY-MM-DD"
                  :editable="false"
                  :clearable="true"
                  placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="是否需要核销" prop="auditType">
          <dictionary v-model="formData.auditType" type-code="needAudit" clearable/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
